//
//  MeatCartViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/23.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatCartViewController.h"
#import "MeatOrderViewController.h"

#import "MeatCartTableViewCell.h"
#import "MeatCartWholePigCell.h"
#import "MeatShopSectionModel.h"
#import "MeatShopRightModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MeatCartSectionView.h"
#import "MeatPayView.h"
#import "MeatTipLabel.h"


#define rightCellIdentifier @"rightCellIdentifier_meatcart"

@interface MeatCartViewController ()<MeatCartCellDelegate>

@property (nonatomic, strong) MeatTipLabel *tipLabel;

@property (nonatomic, strong) MeatPayView *footer;
@property (nonatomic, strong) NSArray *leftArray;
@property (nonatomic, strong) NSMutableArray *aimsArr;


@end

@implementation MeatCartViewController

#pragma mark - view life cycle

- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = @"购物车";
        
        [self.baseNavView.rightNavBtn setTitle:@"编辑" forState:UIControlStateNormal];
        self.baseNavView.rightNavBtn.hidden = NO;
        self.baseNavView.rightNavBtn.isNeedAnimation = YES;
    }
   
    {
        __block BOOL selected = NO;
        @weakify(self);
        self.baseNavView.rightNavBtn.tapBlock = ^{
            @strongify(self);
            if (selected) {
                selected = NO;
                [self.baseNavView.rightNavBtn setTitle:@"编辑" forState:UIControlStateNormal];
                self.footer.type = MeatPayType_WholeChoose;
            }else{
                selected = YES;
                [self.baseNavView.rightNavBtn setTitle:@"完成" forState:UIControlStateNormal];
                self.footer.type = MeatPayType_Edit;
            }
        };
    }

    {
        [self.view addSubview:self.tipLabel];
        [self.view addSubview:self.footer];
    }
    
}


- (void)setupLayout{
    
    _tipLabel.mj_y = self.baseNavView.bottom;
    self.tableView.mj_y = _tipLabel.bottom;
    self.tableView.height = KScreenHeight - (_tipLabel.height + _footer.height +TJ_NavBarHeight);
    _footer.mj_y = self.tableView.bottom ;

}

- (void)initData{
    
    _leftArray = [[NSArray alloc] initWithObjects:@"促销活动",@"臀尖肉",@"五花肉",@"坐臀肉",@"前腿肉",@"前排肉",@"奶脯肉",@"弹子肉", nil];
    
    NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"newsData" ofType:@"json"]];
    
    @weakify(self);
    [_leftArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @strongify(self);
        
        MeatShopSectionModel *model = [[MeatShopSectionModel alloc] init];
        model.name = (NSString *) obj;
        model.section = idx;
        
        NSMutableArray *aims = [NSMutableArray array];
        for (NSInteger i = 0; i<= idx; i++) {
            
            NSArray *rightArray = [NSArray yy_modelArrayWithClass:[MeatShopRightModel class] json:jsonData];
            
            MeatShopRightModel *cellModel = [[MeatShopRightModel alloc] init];
            cellModel = rightArray[i];
            [aims addObject:cellModel];
        }
        
        model.rows = aims;
        [self.aimsArr addObject:model];
    }];
}


#pragma mark - 折叠按钮点击代理

- (void)clickFoldLabel:(MeatCartTableViewCell *)cell{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    MeatShopRightModel *model = sectionModel.rows[indexPath.row];
    
    model.isOpening = !model.isOpening;
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}

#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.aimsArr.count;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    MeatShopSectionModel *model = self.aimsArr[section];
    return model.rows.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        return 110;
    }

    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    
    if (sectionModel.rows.count > 0)
    {
        MeatShopRightModel *model = [sectionModel.rows objectAtIndex:indexPath.row];
        if (model.isOpening) {
            // 使用不缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }else{
            // 使用缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier cacheByIndexPath:indexPath configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }
    } else{
        
        return 10;
    }
}

// 处理折叠cell高度
-(void)handleCellHeightWithNewsCell:(id)cell indexPath:(NSIndexPath *)indexPath{
    
    MeatCartTableViewCell *newsCell = (MeatCartTableViewCell *)cell;
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    newsCell.newsModel = sectionModel.rows[indexPath.row];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 51;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (tableView == self.tableView && section <_leftArray.count) {
        
        MeatCartSectionView *sectionView = [[MeatCartSectionView alloc] init];
        MeatShopSectionModel *model = self.aimsArr[section];
        sectionView.shopName = model.name;
        sectionView.isChicked = model.isChicked;
        
        kWeakSelf(self);
        sectionView.dealCartSectionBlock = ^(UIButton *btn) {
            
            MeatShopSectionModel *sectionModel = weakself.aimsArr[section];
            
            if (sectionModel.isChicked) {
                
                sectionModel.isChicked = NO;
                [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    MeatShopRightModel *model = (MeatShopRightModel *)obj;
                    model.isChicked = NO;
                }];
                
            }else{
                
                sectionModel.isChicked = YES;
                [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MeatShopRightModel *model = (MeatShopRightModel *)obj;
                    model.isChicked = YES;
                }];
            }

            [weakself localReloadTableViewBySection:section];
        };
        
        return sectionView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    MeatShopRightModel *model = sectionModel.rows[indexPath.row];

    if (indexPath.section == 2) {
        MeatCartWholePigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatCartWholePigCell"];
        cell.newsModel = model;
        
        kWeakSelf(self);
        cell.chooseCartBlock = ^(UIButton *btn) {
            model.isChicked = model.isChicked ?NO :YES;
            [weakself localReloadTableViewBySection:indexPath.section];
        };
        return cell;
    }

    MeatCartTableViewCell *newsCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
    newsCell.cellDelegate = self;
    newsCell.newsModel = model;
    
    //单个选择cellBlock
    kWeakSelf(self);
    newsCell.chooseCartBlock = ^(UIButton *btn) {
        model.isChicked = model.isChicked ?NO :YES;
        [weakself localReloadTableViewBySection:indexPath.section];
    };
    
    return newsCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - setter and getter

- (MeatTipLabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[MeatTipLabel alloc] init];
        _tipLabel.height = 34;
        
        NSString *contentStr = @" 购物车中有3件商品已无货，点击查看";
        NSMutableAttributedString *aims = [contentStr createAttributingByIcon:@"meat_cart_tip" downIndexImage:nil textColor:UIColorFromRGB(0xEC8C00) font:mFont(12)];
        _tipLabel.attributedText = aims;
    }
    return _tipLabel;
}


- (MeatPayView *)footer{
    if (!_footer) {
        _footer = [[MeatPayView alloc] init];
        _footer.type = MeatPayType_WholeChoose;
        
        //全选Block
        kWeakSelf(self)
        _footer.chooseCartBlock = ^(UIButton *btn) {
            
            if (btn.selected) {
                [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                    sectionModel.isChicked = NO;
                    [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        MeatShopRightModel *model = (MeatShopRightModel *)obj;
                        model.isChicked = NO;
                        [weakself.tableView reloadData];
                    }];
                }];

            }else{
                [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                    sectionModel.isChicked = YES;
                    
                    [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        MeatShopRightModel *model = (MeatShopRightModel *)obj;
                        model.isChicked = YES;
                        [weakself.tableView reloadData];
                    }];
                }];
            }
        };
        
        
        //支付Block
        _footer.payCartBlock = ^{
            
            MeatOrderViewController *vc = [[MeatOrderViewController alloc] init];
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        
        //清除Block
        _footer.clearCartBlock = ^{
            
        };
        
        //删除Block
        _footer.deleteCartBlock = ^{
            
            [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                NSMutableArray *aims = [NSMutableArray arrayWithArray:sectionModel.rows];

                [aims enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MeatShopRightModel *model = (MeatShopRightModel *)obj;
                    if (model.isChicked) {
                        [aims removeObject:model];
                    }
                }];
                
                sectionModel.rows = aims;
            }];
            
            [weakself.tableView reloadData];

        };
    }
    return _footer;
}


- (NSMutableArray *)aimsArr{
    if (!_aimsArr) {
        _aimsArr = [NSMutableArray array];
    }
    return _aimsArr;
}

#pragma mark - other methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat sectionHeaderHeight = 51;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark - override methods

- (void)registerTableViewCell{
    
    [self.tableView registerClass:[MeatCartTableViewCell class] forCellReuseIdentifier:rightCellIdentifier];
    [self.tableView registerClass:[MeatCartWholePigCell class] forCellReuseIdentifier:@"MeatCartWholePigCell"];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 10)];
    view.backgroundColor = mBackgroudColor;
    self.tableView.tableFooterView = view;
}


@end
